const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("uni-id-base-order");
const $ = db.command.aggregate;
module.exports = class OrderService extends Service {
  async add(){
		const ctx=this.ctx
		const dbJQL = uniCloud.databaseForJQL({
			event:ctx.envent,
			context:ctx.context
		})
		const time=(new Date()).getTime()
		ctx.data.user_id=ctx.uid
		ctx.data.create_time=time
		dbJQL.setUser({
			uid: ctx.uid, 
			role: ["admin"],
			permission: []
		})
		await dbJQL.collection('goods_cart').where({
			user_id:ctx.uid,
			sku_id:dbCmd.in(ctx.data.sku_ids)
		}).remove()
		const res=await dbJQL.collection('uni-id-base-order').add(ctx.data)
		if(res.code==0){
			return response.success(res.id)
		}else{
			return response.fail(res.message)
		}
  }
	async list(){
		const ctx=this.ctx
		ctx.data.user_id=ctx.uid
		const page_size=ctx.data.page_size||100
		const page_num=ctx.data.page_num||1
		const where={
			user_id:ctx.uid
		}
		if(ctx.data.status!=undefined){
			where.status=ctx.data.status
		}
		const res=await collection.aggregate().lookup({
			from: 'opendb-mall-sku',
			localField: 'sku_ids',
			foreignField: '_id',
			as: 'skus'
			})
			.lookup({
				from: 'uni-id-address',
				localField: 'address_id',
				foreignField: '_id',
				as: 'addresses',
			})
			.lookup({
				from: 'opendb-mall-goods',
				localField: 'goods_ids',
				foreignField: '_id',
				as: 'goods'
			}).match(where).limit(page_size).skip((page_num-1)*page_size).end();
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('查询失败');
		}
	}
	async getOne(){
		const ctx=this.ctx
		const res=await collection.doc(ctx.data.id).get()
		if(res.affectedDocs>=0){
			return response.success(res.data[0]);
		}else{
			return response.fail('查询失败');
		}
	}
};